﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.WPF.Theme.FrameworkControl.CustomWinodw
 * 唯一标识：1196831b-0ad3-4760-b50b-7960860e73f4
 * 文件名：FolderPicker
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2024/10/10 10:18:26
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Vampirewal.Core.Interface;

namespace Vampirewal.Core.WPF.Theme;

/// <summary>
/// FolderPicker.xaml 的交互逻辑
/// </summary>
[VampirewalIoCRegister("FolderPicker", RegisterType.Transient)]
[ObservableObject]
public partial class FolderPicker : MainWindowBase, IFolderPickerWindow
{
    private string selectedPath;

    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public FolderPicker(IVampirewalCoreDialogMessage dialog)
    {
        InitializeComponent();
        this.DataContext = this;
        Dialog= dialog;

        FolderInfos = new ObservableCollection<FolderInfo>();


    }

    public string SelectedPath { get => selectedPath; private set { selectedPath = value;OnPropertyChanged(); } }

    public ObservableCollection<FolderInfo> FolderInfos { get; set; }
  

    public void LoadDirectory(string defaultPath="")
    {
        if (!string.IsNullOrEmpty(defaultPath))
        {
            if (Directory.Exists(defaultPath))
            {
                LoadFolderList(defaultPath);

                SelectedPath= defaultPath;

                DirectoryInfo info=new DirectoryInfo(defaultPath);

                SelectedFolder = new FolderInfo()
                {
                    Name= info.Name,
                    DI=info,
                    Path=defaultPath
                };
            }
        }

        foreach (var drive in Directory.GetLogicalDrives())
        {
            var driveInfo = new DriveInfo(drive);
            var treeViewItem = new TreeViewItem { Header = driveInfo.Name, Tag = driveInfo };
            treeViewItem.Expanded += TreeViewItem_Expanded;
            FolderTreeView.Items.Add(treeViewItem);
        }
    }

    private void LoadFolderList(string path)
    {
        FolderInfos.Clear();

        foreach (var item in Directory.GetDirectories(path).Select(s => new DirectoryInfo(s)))
        {
            FolderInfo info = new FolderInfo()
            {
                Name = item.Name,
                Path = item.FullName,
                DI=item
            };

            FolderInfos.Add(info);
        }
    }

    private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
    {
        var treeViewItem = sender as TreeViewItem;
        if (treeViewItem != null && treeViewItem.Items.Count == 0)
        {

            DirectoryInfo directoryInfo = null;
            if (treeViewItem.Tag is DriveInfo di)
            {
                directoryInfo = di.RootDirectory;
            }
            else if(treeViewItem.Tag is DirectoryInfo di2)
            {
                directoryInfo = di2;
            }

            if (directoryInfo != null)
            {
                try
                {
                    foreach (var directory in directoryInfo.GetDirectories())
                    {
                        var subItem = new TreeViewItem { Header = directory.Name, Tag = directory };
                        subItem.Expanded += TreeViewItem_Expanded;
                        treeViewItem.Items.Add(subItem);
                    }

                    LoadFolderList(directoryInfo.FullName);
                }
                catch (UnauthorizedAccessException) { }
            }
        }
    }

    private void FolderTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        if (FolderTreeView.SelectedItem is TreeViewItem selectedItem && selectedItem.Tag is DirectoryInfo directoryInfo)
        {
            SelectedPath = directoryInfo.FullName;
        }
    }

    private void OkButton_Click(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(SelectedPath))
        {
            DialogResult = true; // 设置为 true 表示选择成功
            Close();
        }
        else
        {
            //MessageBox.Show("请先选择一个文件夹。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);

            Dialog.ShowPopupWindow(new PopupWindowSetting()
            {
                Message= "请先选择一个文件夹。",
                Type= MessageType.Error,
                OwnerWindow=this,
                IsKeepOpen= false,
            });
        }
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false; // 设置为 false 表示取消选择
        Close();
    }

    private FolderInfo? SelectedFolder { get; set; }

    private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        // 获取被双击的行
        var dataGrid = sender as DataGrid;
        if (dataGrid != null)
        {
            var selectedItem = dataGrid.SelectedItem as FolderInfo;
            if (selectedItem != null)
            {
                SelectedFolder=selectedItem;

                SelectedPath = selectedItem.Path;

                LoadFolderList(SelectedPath);
            }
        }
    }

    private void findParent_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedFolder!=null)
        {
            var parent= Directory.GetParent(SelectedPath);

            if (parent != null)
            {
                SelectedPath = parent.FullName;

                SelectedFolder = new FolderInfo()
                {
                    Name=parent.Name,
                    Path=parent.FullName,
                    DI=parent
                };

                LoadFolderList(SelectedPath);
            }
            else
            {
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = "已到根盘符，请选择文件夹",
                    Type = MessageType.Error,
                    OwnerWindow = this,
                    IsKeepOpen = false,
                });
            }
        }
    }
}

public class FolderInfo:ObservableObject
{
    public string Name { get; set; }

    public string Path { get; set; }

    public DirectoryInfo DI { get; set; }
}